package com.atguigu.gulimall.order.web;

import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.vo.OrderConfirmVo;
import com.atguigu.gulimall.order.vo.OrderSubmitVo;
import com.atguigu.gulimall.order.vo.SubmitOrderResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * @Description :
 * @Author : mayp
 * @Date: 2020-12-27 18:51
 */
@Controller
public class OrderWebController {
    @Autowired
    private OrderService orderService;

    /**
     * 购物车去结算，需要跳转到订单的结算页面，
     *  结算页面需要先验证客户是否已经登录，如果未登录需要先登录。在登录拦截器中已经做了拦截，如果没有登录，会直接对请求拦截。
     */
    @GetMapping("/toTrade")
    public String toTrade(Model model){
        OrderConfirmVo confirmVo = orderService.confirmOrder();
        model.addAttribute("confirm",confirmVo);
        return "confirm";
    }

    /**
     * 结算下单，点击提交按钮后跳转的路径。下单功能
     */
    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo vo, Model model, RedirectAttributes redirectAttributes){
        SubmitOrderResponseVo response = orderService.submitOrder(vo);
        System.out.println("订单的所有数据："+vo);
        if (response.getCode() == 0){
            // 下单成功--来到支付选择页
            model.addAttribute("submitOrderResp",response);
            return "pay";
        }else {
            // 下单失败--返回下单页，并提示是什么原因失败。
            String msg = "下单失败";
            switch (response.getCode()){
                case 1: msg+= "订单信息过期，请刷新再次提交"; break;
                case 2: msg+= "订单商品价格发生变化，请确认后再次提交"; break;
                case 3: msg+= "库存锁定失败，商品库存不足";break;
            }
            // 如果下单失败就可以回到下单确认页，让用户重新确认下订单信息
            redirectAttributes.addFlashAttribute("msg",msg);
            return "redirect:http://order.gulimall.com/toTrade";
        }
    }
}
